import { ReactElement, useEffect, useState } from 'react'
import { Button, Radio, Space, message } from 'antd';
import style from './index.module.less'
import Table from '@components/table'
import { PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import { getColumn } from './util'
import { getListRequest } from './ajax'
import { awaitWrap, confirmAction, formatDate } from '@src/assets/js/tool'
import { connect, useSelector } from 'react-redux'
import { UserInfo } from '@src/components/schema/basic'
import { INIT_BASIC_STATE } from '@src/redux/reducers/basic'
import { setSearch } from '@js/tool'
import { ConditionSchema } from '@components/schema/condition'
import { SystemQuestionSchema } from '@components/schema/systemQuestion'
import AdminEditModal from './components/adminEditModal'
import DetailModal from './components/detailModal'
import EditModal from './components/editModal'
import { json2Excel } from '@src/assets/js/excel';

async function getTaskList (data: { [k: string]: any }, userInfo: UserInfo, setDataSource: (v: Object[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void, setCondition: (v: ConditionSchema[]) => void): Promise<void> {
  setLoading(true)
  const condition: ConditionSchema[] = []
  if (data.status === '已解决') {
    condition.push({ k: 'status', o: 'in', v: '完成,暂不处理' })
  } else if (data.status === '未解决') {
    condition.push({ k: 'status', o: 'not in', v: '完成,暂不处理' })
  }
  setCondition(condition)
  const [e, d] = await awaitWrap(getListRequest(
    JSON.stringify(condition),
    data.page,
    data.limit
  ))
  setLoading(false)
  if (e === null && d !== null) {
    if (typeof d.total === 'number') {
      setTotal(d.total)
    }
    if (d.list instanceof Array) {
      d.list.forEach((li, i) => {
        li.orderno = i + 1 + (data.page - 1) * data.limit
      })
      setDataSource(d.list)
    }
  }
}

// 获取当前查询条件的全部数据，并下载excel
async function downloadExcel (condition: ConditionSchema[]) {
  const current = 1
  const pageSize = 1000000
  const hide = message.loading('导出中', 300)
  const [e, d] = await awaitWrap(getListRequest(
    JSON.stringify(condition),
    current,
    pageSize
  ))
  hide()
  if (e === null && d !== null) {
    const list = d.list.map((l, i) => {
      return {
        序号: pageSize * (current - 1) + i + 1,
        标题: l.title,
        问题类型: l.type,
        问题描述: l.content,
        创建时间: formatDate(l.create_datetime),
        创建人: l.operator,
        状态: l.status,
        处理时间: formatDate(l.complete_datetime),
        处理结果: l.remark
      }
    })
    json2Excel([{ data: list, sheetname: '系统问题反馈' }], '系统问题反馈')
  }
}

function Main (): ReactElement {
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<Object[]>([])
  const [formData, setFormData] = useState<{ [k: string]: any }>({})
  const [modifyData, setModifyData] = useState<SystemQuestionSchema | null>(null)
  const [detailVisible, setDetailVisible] = useState(false)
  const [editVisible, setEditVisible] = useState(false)
  const [adminVisible, setAdminVisible] = useState(false)
  const [params, setParams] = useState<{[k: string]: any}>({status: '全部'})
  const [condition, setCondition] = useState<ConditionSchema[]>([])
  const {userInfo} = useSelector((state: {basic: INIT_BASIC_STATE}) => {
    return {
      userInfo: state.basic.userInfo
    }
  })
  function refreshFn (): void {
    getTaskList(formData, userInfo, setDataSource, setTotal, setLoading, setCondition).catch(e => console.error(e))
    setModifyData(null)
    setDetailVisible(false)
    setEditVisible(false)
    setAdminVisible(false)
  }
  return (
    <div className={style.container}>
      <EditModal data={modifyData} visible={editVisible} refreshFn={refreshFn} hide={() => { setEditVisible(false); setModifyData(null) }} />
      <AdminEditModal data={modifyData} visible={adminVisible} refreshFn={refreshFn} hide={() => { setAdminVisible(false); setModifyData(null) }} />
      <DetailModal data={modifyData} visible={detailVisible} refreshFn={refreshFn} hide={() => { setDetailVisible(false); setModifyData(null) }} />
      <div className={style.body}>
        <div className={style.split}></div>
        <div className={style.table}>
          <div className={style['operate-line']}>
            <Space>
              <Button type='primary' icon={<PlusOutlined />} onClick={() => { setModifyData(null); setEditVisible(true) }}>新增问题</Button>
              <Button onClick={() => confirmAction('您确定要导出excel吗？', () => downloadExcel(condition))} icon={<DownloadOutlined />}>导出excel</Button>
            </Space>
            <Radio.Group value={params.status} onChange={v => setParams({ ...params, status: v.target.value })}>
              <Radio.Button value='全部'>全部</Radio.Button>
              <Radio.Button value='已解决'>已解决</Radio.Button>
              <Radio.Button value='未解决'>未解决</Radio.Button>
            </Radio.Group>
          </div>
          <Table params={params} setParams={setParams} loading={loading} columns={getColumn(userInfo, refreshFn, setModifyData, setDetailVisible, setEditVisible, setAdminVisible)} total={total} dataSource={dataSource} onChange={async d => {
            setFormData(d)
            await getTaskList(d, userInfo, setDataSource, setTotal, setLoading, setCondition)
          }} />
        </div>
      </div>
    </div>
  )
}

export default Main
